<template>
  <div class="main">
    
    <div class="form">
      <el-form :rules="rules" ref="form" label-width="120px" :model="form">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-radio v-model="form.isShow" :label="0">隐藏</el-radio>
          <el-radio v-model="form.isShow" :label="1">显示</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { addClassify,getClassifyById,updateClassify } from '@/api/classify'
export default {
  name:'classify',
  data(){
    return {
      rules:{
        name:[
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        isShow:[
          { required: true, message: '请选择分类是否显示', trigger: 'change' },
        ]
      },
      form:{
        name:'',
        isShow:1
      },
      type:'new'
    }
  },
  created(){
    let classifyId = this.$route.query.classifyId
    console.log('classifyId:',classifyId)
    if(classifyId){
      this.type = 'edit'
      // 如果classifyId存在，则为编辑
      getClassifyById(classifyId).then(res=>{
        if(res.code === 0){
          this.form = res.data
        }else{
          this.$message.error(`获取id为${classifyId}的分类失败`)
        }
      })
    }
  },
  methods:{
    submit(){
      this.$refs['form'].validate((valid,errorObj)=>{
        if(valid){
          if(this.type === 'new'){
            // 新增
            addClassify(this.form).then(res=>{
              if(res.code === 0){
                this.$message.success('新增分类成功')
                this.$router.push('/classify')
              }else{
                this.$message.error('新增分类失败')
              }
            })
          }else{
            // 编辑
            updateClassify(this.form).then(res=>{
              if(res.code === 0){
                this.$message.success('更新分类成功')
                this.$router.go(-1)
              }else{
                this.$message.error('更新分类失败')
              }
            })
          }
          
        }else{
          // this.$message.error(JSON.stringify(errorObj))
          return false
        }
      })
      
    }
  }
}
</script>
<style lang="scss" scoped>
.main{
  padding:10px 20px;
  .title{

  }
  .form{
    margin-top:20px;
  }
}
</style>
